<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true">
      <el-form-item label="商品代码" prop="goodsCode">
        <el-input v-model="form.goodsCode" placeholder="请输入商品编号" disabled/>
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="form.goodsName" placeholder="请输入商品名称"  />
      </el-form-item>
      <el-form-item label="仓库编号" prop="warehouseCode">
        <el-select v-model="form.warehouseCode" placeholder="请选择仓库编号" >
          <el-option
            v-for="w in warehouseList"
            :key="w.id"
            :label="w.warehouseName"
            :value="w.warehouseCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="选择商品分类" :style="{width: '100%'}">
          <el-option
            v-for="c in categoryChildList"
            :key="c.id"
            :label="c.cname"
            :value="c.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandId">
        <el-select v-model="form.brandId" placeholder="选择品牌名称" :style="{width: '100%'}">
          <el-option
            v-for="b in brandList"
            :key="b.id"
            :label="b.bname"
            :value="b.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="form.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="商品详情" prop="goodsDetails">
        <el-input v-model="form.goodsDetails" placeholder="请输入商品详情" />
      </el-form-item>
      <el-form-item label="商品描述" prop="goodsMark" >
        <el-input v-model="form.goodsMark" type="textarea" placeholder="请输入内容" />
      </el-form-item>

      <!--        插入规格开始-->
      <el-button type="primary" plain  @click="insertSpecification()" icon="el-icon-plus" size="mini" style="width: 200px;display: block">插入规格</el-button>
      <el-form v-for="(specification, index) in form.bmSpecificationList" :key="index" :model="specification" :rules="rules" label-width="80px" :inline="true" style="background: #d0d9fa;border: white 1px solid">
        <div style="display: flex; justify-content: flex-end;">
          <el-button type="danger" icon="el-icon-minus" circle class="minus" @click="delSpecification(index)"></el-button>
        </div>
        <el-row>
          <el-col>
            <el-form-item label="规格名称" prop="specificationName">
              <el-input v-model="specification.specificationName" placeholder="请输入规格名称" />
            </el-form-item>
            <el-form-item label="零售价" prop="retailPrice">
              <el-input v-model="specification.retailPrice" placeholder="请输入零售价" />
            </el-form-item>
            <el-form-item label="库存量" prop="stock">
              <el-input v-model="specification.stock" placeholder="请输入库存量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col >
            <el-form-item label="条形码" prop="barCode">
              <el-input v-model="specification.barCode" placeholder="请输入条形码" />
            </el-form-item>
            <el-form-item label="保质期" prop="qualityPeriod">
              <el-input v-model="specification.qualityPeriod" placeholder="请输入保质期" style="width: 50%"/>
              <el-select v-model="selectedPeriodUnit" placeholder="请选择单位" style="width: 20%">
                <el-option label="天" value="天"></el-option>
                <el-option label="月" value="月"></el-option>
                <el-option label="年" value="年"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="生产地" prop="productionPlace">
              <el-input v-model="specification.productionPlace" placeholder="请输入生产地" />
            </el-form-item>
            <el-form-item label="购买上限" prop="purchaseLimit">
              <el-input v-model="specification.purchaseLimit" placeholder="请输入购买上限" />
            </el-form-item>
            <el-form-item label="起订量" prop="minOrderQuantity">
              <el-input v-model="specification.minOrderQuantity" placeholder="请输入起订量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="起订价" prop="minOrderPrice">
          <el-input v-model="specification.minOrderPrice" placeholder="请输入起订价" />
        </el-form-item>
        <el-form-item label="是否推荐" prop="isRecommond">
          <el-select v-model="specification.isRecommond" placeholder="请选择推荐状态">
            <el-option label="推荐" :value="1"></el-option>
            <el-option label="未推荐" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片上传" prop="goodsImgUrl">
          <uploadImage v-model="specification.goodsImgUrl"></uploadImage>
        </el-form-item>
      </el-form>
      <!--        插入规格结束-->
    </el-form>
    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">
        <el-button type="primary" @click="submitForm()" >提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {
  getGoods,
  addGoods,
  updateGoods,
  getWarehouseList,
  getMaxCode
} from "@/api/ruoyi-goods/goods";
import {secondList} from "@/api/ruoyi-goods/category";
import {listBName} from "@/api/ruoyi-goods/brand";
import uploadImage from "@/components/ImageUpload/index.vue";
  export default {
    name: "Goods",
    components: {uploadImage},
    data() {
      return {
        // 仓库列表绑定下拉框
        warehouseList:[],
        // 类别列表绑定下拉框
        categoryChildList: [],
        brandList:[],
        // 表单参数
        form: {
            bmSpecificationList:[{
              specificationName:'',
              retailPrice:'',
              stock: 0,
              barCode:'',
              qualityPeriod:'',
              productionDate:'',
              productionPlace:'',
              purchaseLimit:'',
              minOrderQuantity:'',
              minOrderPrice:'',
              goodsImgUrl:''
            }],
        },
        selectedPeriodUnit: '', // 保存选中的单位
        // 表单校验
        rules: {
          goodsCode: [
            { required: true, message: "商品编号不能为空", trigger: "blur" }
          ],
          goodsName: [
            { required: true, message: "商品名称不能为空", trigger: "blur" }
          ],
          categoryId: [
            { required: true, message: "商品分类不能为空", trigger: "blur" }
          ],
          warehouseCode: [
            { required: true, message: "仓库名称不能为空", trigger: "blur" }
          ],
          brandId: [
            { required: true, message: "品牌名称不能为空", trigger: "blur" }
          ],
          specificationName:[
            { required: true, message: "规格名称不能为空", trigger: "blur" }
          ],
          isRecommond:[
            {required: true, message: "是否推荐不能为空", trigger: "blur"}
          ]
        }
      };
    },
    activated() {
      this.getWarehouseNameList();
      this.getCategorySecondNameList();
      this.getBrandList();
      this.getMaxGoodsCode();
      let result = this.$route.params.id
      console.log(result)
      if (result > 0) {
        getGoods(this.$route.params.id).then(response => {
          console.log("Update", response);
          this.form = response.data;
          // 遍历this.form.bmSpecificationList并对每个对象进行操作
          this.form.bmSpecificationList.forEach(spec => {
            // Assign last character of qualityPeriod to selectedPeriodUnit
            const lastCharacter = spec.qualityPeriod.slice(-1);
            this.selectedPeriodUnit = lastCharacter;

            // Assign qualityPeriod without last character to spec.qualityPeriod
            spec.qualityPeriod = spec.qualityPeriod.slice(0, -1);
          })
        })
      }
    },
    computed: {
      filteredSecondCategoryList() {
        return this.categoryChildList.filter(c => c.parentId === this.selectedFirstCategoryId);
      },
    },
    watch: {
      selectedFirstCategoryId() {
        this.selectedSecondCategoryId = null;
      },
      selectedSecondCategoryId(newValue) {
        this.queryParams.categoryId = newValue;
      },
      $route(){
        this.$router.go();
      }
    },
    methods: {
      insertSpecification(){
        const emptyForm = {
          specificationName: '',
          retailPrice: '',
          stock: 0,
          barCode: '',
          qualityPeriod: '',
          productionPlace: '',
          purchaseLimit: '',
          minOrderQuantity: '',
          minOrderPrice: '',
          goodsImgUrl: ''
        };
        this.form.bmSpecificationList.push(emptyForm);
        console.log("<>",this.form);
      },
      getWarehouseNameList(){
        getWarehouseList().then(response => {
          this.warehouseList = response.data;
        })
      },
      getBrandList(){
        listBName().then(response => {
          this.brandList = response.data;
        })
      },
      getCategorySecondNameList(){
        secondList().then(response => {
          this.categoryChildList = response.data;
        })
      },
      getMaxGoodsCode(){
        getMaxCode().then(response => {
          console.log("33",response);
          let oldCode = parseInt(response) + 1;//将数值类型与1相加
          let newCode = oldCode .toString().padStart(response.length, '0'); //保持相同位数,前面补0
          this.form.goodsCode = newCode;
        })
      },
      // 返回按钮
      close() {
        const obj = { path: "/goods/goods" };
        this.$tab.closeOpenPage(obj);
        this.reset();
        this.getMaxGoodsCode();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          goodsCode: null,
          goodsName: null,
          warehouseCode: null,
          categoryId: null,
          brandId: null,
          sort: null,
          goodsDetails: null,
          goodsMark: null,
          createTime: null,
          isDeleted: null,
          bmSpecificationList:[{
            specificationName:'',
            retailPrice:'',
            stock: 0,
            barCode:'',
            qualityPeriod:'',
            productionDate:'',
            productionPlace:'',
            purchaseLimit:'',
            minOrderQuantity:'',
            minOrderPrice:'',
            goodsImgUrl:''
          }],
        };
        this.selectedPeriodUnit= null;
        this.resetForm("form");
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            console.log("oldForm=",this.form);
            // 遍历规格列表，将 selectedPeriodUnit 合并到 qualityPeriod
            this.form.bmSpecificationList.forEach(specification => {
              if (specification.qualityPeriod) {
                specification.qualityPeriod += this.selectedPeriodUnit || '';
              }
            });
            console.log("newForm=",this.form);
            if (this.form.id != null) {
              updateGoods(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.close();
                // location.href = "http://localhost/goods/goods";
              });
            } else {
              addGoods(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.close();
              });
            }
          }
        });
      },
      delSpecification(index){
        this.form.bmSpecificationList.splice(index, 1);
      },
    }
  };
</script>
